package Thread_Test;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Ticket implements Runnable {
    private int ticket = 1000;
    private Lock lock = new ReentrantLock();

    @Override
    public void run() {
        while (ticket > 0) {
            //临界资源问题使用同步代码块解决----1
            //使用this指针也可以作为锁对象
            //static函数可以使用类.class作为锁对象
//            synchronized (Ticket.class) {
//                if (ticket > 0) {
////                    System.out.println(Thread.currentThread().getName() + ":" + ticket);
////                    ticket--;
////                } else {
////                    System.out.println("票数为0, 抢票失败");
////                }
//            }
            //使用互斥锁
            lock.lock();
            if (ticket > 0) {
                System.out.println(Thread.currentThread().getName() + ":" + ticket);
                ticket--;
            } else {
                System.out.println("票数为0, 抢票失败");
            }
            lock.unlock();
        }
    }
}